#define _CRT_SECURE_NO_WARNINGS 1

class Solution {
public:
    int longestValidParentheses(string s)
    {
        int n = s.size();
        vector<int> dp(n);
        int ret = 0;

        for (int i = 1; i < n; i++)
        {
            if (s[i] == ')')
            {
                if (i - dp[i - 1] - 1 >= 0 && s[i - dp[i - 1] - 1] == '(')
                {
                    dp[i] = dp[i - 1] + 2;
                    if (i - dp[i - 1] - 2 >= 0) dp[i] += dp[i - dp[i - 1] - 2];
                }

                ret = max(ret, dp[i]);
            }
        }

        return ret;
    }
};

class Solution {
public:
    bool canPartition(vector<int>& nums)
    {
        int m = nums.size();
        int sum = 0;
        for (auto e : nums) sum += e;
        if (sum % 2 == 1) return false;

        vector<bool> dp(sum / 2 + 1);
        dp[0] = true;
        for (int i = 1; i <= m; i++)
        {
            for (int j = sum / 2; j >= nums[i - 1]; j--)
            {
                dp[j] = dp[j] || dp[j - nums[i - 1]];
            }
        }

        return dp[sum / 2];
    }
};

class Solution {
public:
    int maxProduct(vector<int>& nums)
    {
        int n = nums.size();
        vector<int> f(n), g(n);
        f[0] = g[0] = nums[0];
        int ret = f[0];

        for (int i = 1; i < n; i++)
        {
            f[i] = max(nums[i], max(f[i - 1] * nums[i], g[i - 1] * nums[i]));
            g[i] = min(nums[i], min(f[i - 1] * nums[i], g[i - 1] * nums[i]));
            ret = max(ret, f[i]);
        }

        return ret;
    }
};

class Solution {
public:
    int lengthOfLIS(vector<int>& nums)
    {
        int n = nums.size();
        vector<int> tmp;

        for (int i = 0; i < n; i++)
        {
            if (tmp.size() == 0 || nums[i] > tmp.back())
            {
                tmp.push_back(nums[i]);
            }
            else
            {
                int left = 0, right = tmp.size() - 1;
                int mid = 0;
                while (left < right)
                {
                    mid = left + (right - left) / 2;
                    if (tmp[mid] >= nums[i])
                    {
                        right = mid;
                    }
                    else left = mid + 1;
                }
                tmp[left] = nums[i];
            }
        }

        return tmp.size();
    }
};